var SocialSecurity = {

    selected_row_id: null,
    objGrid: null,

    init: function () {
        var self = this;

        self.objGrid = $('#flex').flexigrid({
            url: $('#table-url').val(),
            reload_after_add: true,
            dataType: 'json',
            colModel: [
                {display: 'ID', name: 'id', width: 20, sortable: false, align: 'left', hide: true},
                {display: 'Category Name', name: 'name', width: 200, sortable: true, align: 'left', hide: false},
                {display: 'Computation', name: 'compute', width: 300, sortable: true, align: 'left', hide: false},
                {display: 'Presentation', name: 'present', width: 300, sortable: true, align: 'left', hide: false}
            ],
            formFields: [
                {type: 'buttom', name: 'New', bclass: 'add', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Edit', bclass: 'edit', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Delete', bclass: 'delete', onpress: self.handleGridEvent},
                {separator: true}
            ],
            searchitems: [
                {display: 'Category Name', name: 'name', isdefault: true}
            ],
            checkboxSelection: true,
            editablegrid: {
                use: false
                //url:$('#table-editable-url').val()
            },
            columnControl: false,
            sortname: "id",
            sortorder: "desc",
            usepager: true,
            useRp: true,
            rp: 15,
            showTableToggleBtn: false,
            height: 300,
            subgrid: {
                use: false
            }
        });

        $('#cancel-btn').click(function () {
            document.getElementById('user-form').reset();
            //$.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
        });
        $('#save-btn').click(function () {
            self.save();
        });

        $("#add-more-btn").live('click', function () {
            self.add_field();
        });

        $("#delete-component-btn").live('click', function () {
            self.remove_field();
        });
    },

    handleGridEvent: function (com, grid, json) {
        if (com == 'New') {
            //SocialSecurity.objGrid.flexBeginAdd();
            //$('#user-form-window #user-form #user_id').val(row_ids[0]);

            $.colorbox({
                inline: true,
                scrolling: false,
                overlayClose: false,
                escKey: false,
                title: 'Form Information',
                href: "#form-window"
            });
        }
        else if (com == 'Edit') {
            if (FlexObject.rowSelectedCheck(SocialSecurity.objGrid, grid)) {
                var row = FlexObject.getSelectedRows(grid);
                //SocialSecurity.objGrid.flexBeginEdit(row[0]);
            }
        }
        else if (com == 'Delete') {
            if (FlexObject.rowSelectedCheck(SocialSecurity.objGrid, grid)) {
                SocialSecurity.delete_(SocialSecurity.objGrid, grid);
            }
        }
    },

    delete_: function (griObject, grid_dom) {
        var self = this;
        var url = $('#table_delete_url').val();
        Jlib.do_delete(griObject, url, grid_dom);
    },

    add_field: function () {
        var tbody = $("#table-components tbody");
        var count = parseInt(tbody.attr('data-count'));
        var num = count + 1;
        var tr = $("<tr />").attr('data-id',num);
        var hidden_order = "<input type='hidden' name='data[SocialSecurity]["+num+"][tier]' value='"+num+"' />";
        var hidden_id = "<input type='hidden' name='data[SocialSecurity]["+num+"][id]'  value='0'  />";
        tr.append($("<td />").html("Tier "+num+ hidden_order+hidden_id));
        var radio =  "<input type='radio' name='data[SocialSecurityCategory][start]' value='"+num+"' />";
        tr.append($("<td />").html(radio));
        var percent_value =  "<input type='text' name='data[SocialSecurity]["+num+"][percent_value]' size='3' style='width: 57px;' class='' value='0' label='Percent Value' validate='required,decimalNumber' />";
        tr.append($("<td />").html(percent_value));
        var presentation_value =  "<input type='text' name='data[SocialSecurity]["+num+"][presentation_value]' size='3' style='width: 57px;' class='' value='0' label='Presentation Value'  validate='required,decimalNumber' />";
        tr.append($("<td />").html(presentation_value));
        tbody.append(tr);
        tbody.attr('data-count',num);
        $.colorbox.resize();
    },

    remove_field: function () {
        //Remove the last fields and reset the counter
        var tbody = $("#table-components tbody");
        var count = parseInt(tbody.attr('data-count'));
        if(count == 1){//IF it's the first field, don't delete
            return;
        }
        $("#table-components tbody tr").each(function(){
            var tr = $(this);
            var id = parseInt(tr.attr('data-id'));
            if(id == count){
                tr.remove();
                var num = count - 1;
                tbody.attr('data-count',num);
                $.colorbox.resize();
                return;
            }
        });
    },

    validateForm: function () {
        var self = this;
        var $return = {status:true,msg:''};
        $("#user-form input").each(function(){
            var input = $(this);
            var input_val = input.val();
            var input_label = input.attr('label');
            var validate = input.attr('validate');
            if(validate){
                var validate_arr = validate.split(',');
                for(var r in validate_arr){
                    var rule = validate_arr[r];
                    if(rule == 'required'){
                        var value = input_val.trim();
                        if(!value){
                            $return.status = false;
                            $return.msg = '* This field is required';
                            input.addClass('error_textfield');
                            break;
                        }
                    }
                    if(rule == 'decimalNumber'){
                        var pattern = eval(/^[\-\+]?(?:\d+|\d{1,3}(?:\d{3})+)(?:\.\d+)$/);
                        if(!pattern.test(input_val)){
                            $return.status = false;
                            $return.msg = '* Invalid floating decimal number. Eg 0.00';
                            input.addClass('error_textfield');
                            break;
                        }
                    }
                }
            }
            return $return;
        });

        //return $return;
    },


    save: function () {
        var self = this;
        /* Validate the form*/
        // var validationStatus = $('#user-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        //  if (validationStatus) {
        var query = $('#user-form').serialize();
        var url = $("#user-form").attr('action');
        /* Send the data to the server and handle the server response */
        $.ajax({
            url: url,
            data: query,
            dataType: 'json',
            type: 'POST',
            success: function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*

                //jLib.message(txt, 'success');
                Jlib.message('Reset Password', txt, 'success');

                if (response.code === 0) {
                    document.getElementById('user-form').reset();
                    //$.validationEngine.closePrompt('.formError', true)
                    $.colorbox.close();
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    Jlib.message('Data Error', txt, 'error');
                }
            },
            error: function (xhr) {
                console.log(xhr.responseText);
                Jlib.serverError();
            }
        });
        // }
    }

};

/* when the page is loaded */
$(document).ready(function () {
    SocialSecurity.init();
});